/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.eng.scc.core.parts;

import com.eng.scc.core.data.Company;
import com.eng.scc.core.data.Driver;
import com.eng.scc.core.util.ImageFinder;
import com.eng.scc.core.view.ApplicationContext;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

/**
 *
 * @author Rafael
 */
public class DriverPicker extends javax.swing.JPanel implements Picker<Driver>
{
    public static Driver pickDriver( Component owner )
    {
        DriverPicker driverPicker = new DriverPicker();
        
        return DefaultPicker.pick( owner, "Selecione um Motorista", driverPicker );
    }
    
    public DriverPicker()
    {
        initComponents();
        
        try
        {
            driversTree.buildTree();
        }
        
        catch ( Exception e )
        {
            ApplicationContext.getInstance().saveLog( e );
        }
    }
    
    @Override
    public Driver getSelectedValue()
    {
        if ( driversTree.getSelectionPath() != null )
        {
            Object o = ((DefaultMutableTreeNode) driversTree.getSelectionPath().getLastPathComponent() ).getUserObject();

            if ( o instanceof Driver)
            {
                return (Driver) o;
            }
        }
        
        return null;
        
        
    }

    @Override
    public boolean validatePicker()
    {
        if ( getSelectedValue() == null )
        {
            JOptionPane.showMessageDialog( this, "Informe um Motorista!" );
            return false;
        }
        
        return true;
    }

    @Override
    public JComponent getComponent()
    {
        return this;
    }

    private void find()
    {
        DefaultMutableTreeNode selectedNode = null;
        if ( this.driversTree.getSelectionPath() != null )
        {
             selectedNode = ( DefaultMutableTreeNode)this.driversTree.getSelectionPath().getLastPathComponent();
        }
            boolean result = false;
            boolean helper = false;

            TreePath path = null;

            DefaultMutableTreeNode firstNodeFound = null;

            if ( ! tfSearch.getText().isEmpty() )
            {
                DefaultMutableTreeNode root = (DefaultMutableTreeNode) driversTree.getModel().getRoot();

                Enumeration e = root.breadthFirstEnumeration();

                while ( e.hasMoreElements() )
                {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();

                    if ( selectedNode != null && 
                         node == selectedNode )
                    {
                        helper = true;
                    }

                    else
                    {
                        if ( node.getUserObject() instanceof Company )
                        {
                            Company c = (Company) node.getUserObject();

                            if ( c.getRealName().toLowerCase().contains( tfSearch.getText().trim().toLowerCase() ) || 
                                 c.getFantasyName().toLowerCase().contains( tfSearch.getText().trim().toLowerCase() ) )
                            {
                                if ( helper )
                                {
                                    result = true;
                                    path = new TreePath( node.getPath() );
                                    break;
                                }

                                else if ( firstNodeFound == null )
                                {
                                    firstNodeFound = node;
                                }
                            }
                        }

                        else if ( node.getUserObject() instanceof Driver )
                        {
                            Driver c = (Driver) node.getUserObject();
                            
                            if ( c.toString().toLowerCase().contains( tfSearch.getText().trim().toLowerCase() ) )
                            {
                                if ( helper )
                                {
                                    result = true;
                                    path = new TreePath( node.getPath() );
                                    break;
                                }

                                else if ( firstNodeFound == null )
                                {
                                    firstNodeFound = node;
                                }
                            }
                        }
                    }
                }

                if ( path == null )
                {
                    if ( firstNodeFound != null )
                    {
                        path = new TreePath( firstNodeFound.getPath() );
                    }

                    else if ( selectedNode != null )
                    {
                        path = new TreePath( selectedNode.getPath() );

                        if ( ! result )
                        {
                            JOptionPane.showMessageDialog( this, "Nenhum resultado encontrado para: " + tfSearch.getText() );
                        }
                    }

                    else
                    {
                        JOptionPane.showMessageDialog( this, "Nenhum resultado encontrado para: " + tfSearch.getText() );
                    }
                }

                driversTree.expandPath( path );
                driversTree.setSelectionPath( path );
                driversTree.scrollPathToVisible( path );
//            }
        }
    }
    
    private void initComponents()
    {
        btSearch.addActionListener( new ActionListener() 
       {
            @Override
            public void actionPerformed( ActionEvent e )
            {
                find();
            }
        });
       
       tfSearch.addActionListener( new ActionListener() 
       {
            @Override
            public void actionPerformed( ActionEvent e )
            {
                find();
            }
        });
       
        setLayout( new GridBagLayout() );
        add( lbSearch, 
             new GridBagConstraints( 0, 0, 1, 1, 0, 0, 
                                        GridBagConstraints.CENTER, 
                                        GridBagConstraints.NONE, 
                                        new Insets( 5, 5, 5, 5 ), 0, 0 ) );
        add( tfSearch, 
             new GridBagConstraints( 1, 0, 1, 1, 1, 0, 
                                        GridBagConstraints.WEST, 
                                        GridBagConstraints.HORIZONTAL, 
                                        new Insets( 5, 5, 5, 5 ), 0, 0 ) );
        add( btSearch, 
             new GridBagConstraints( 2, 0, 1, 1, 0, 0,  
                                        GridBagConstraints.CENTER, 
                                        GridBagConstraints.NONE, 
                                        new Insets( 5, 5, 5, 5 ), 0, 0 ) );
        
        scrollTree.setViewportView( driversTree );
        btSearch.setIcon( ImageFinder.getImageIcon( "bt_search.png") );
        
        add( scrollTree, 
             new GridBagConstraints( 0, 1, 3, 1, 1, 1, 
                                        GridBagConstraints.CENTER, 
                                        GridBagConstraints.BOTH, 
                                        new Insets( 5, 5, 5, 5 ), 0, 0 ) );
    }
    
    private JLabel lbSearch = new JLabel( "Buscar:" );
    private JTextField tfSearch = new JTextField();
    private JButton btSearch = new JButton();
    private DriversTree driversTree = new DriversTree();
    private JScrollPane scrollTree = new JScrollPane();
}

